<!-- 题库管理 -->
<template>
  <div class="app-container">
    <!-- 搜索工具栏 -->
    <div class="toolbar">
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="科目">
          <el-input
            v-model="queryParams.subject"
            placeholder="科目"
            clearable
          />
        </el-form-item>
        <el-form-item label="难度">
          <el-select
            v-model="queryParams.difficulty"
            placeholder="难度"
            clearable
          >
            <el-option label="简单" value="EASY" />
            <el-option label="中等" value="MEDIUM" />
            <el-option label="困难" value="HARD" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <div class="toolbar-buttons">
        <el-button type="success" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增题目
        </el-button>
        <el-upload
          class="upload-button"
          action="/api/questions/import"
          :show-file-list="false"
          :on-success="handleImportSuccess"
          :on-error="handleImportError"
          accept=".xlsx,.xls"
        >
          <el-button type="primary">
            <el-icon><Upload /></el-icon>
            导入题目
          </el-button>
        </el-upload>
      </div>
    </div>

    <!-- 题目列表 -->
    <el-table v-loading="loading" :data="questionList" style="width: 100%">
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column
        prop="questionText"
        label="题目内容"
        show-overflow-tooltip
      />
      <el-table-column prop="subject" label="科目" width="120" />
      <el-table-column prop="questionType" label="类型" width="100">
        <template #default="{ row }">
          <el-tag>单选题</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="difficulty" label="难度" width="100">
        <template #default="{ row }">
          <el-tag :type="getDifficultyType(row.difficulty)">
            {{ getDifficultyText(row.difficulty) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="score" label="分值" width="80" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="科目" prop="subject">
          <el-input v-model="form.subject" placeholder="请输入科目" />
        </el-form-item>
        <el-form-item label="题目内容" prop="questionText">
          <el-input
            v-model="form.questionText"
            type="textarea"
            :rows="3"
            placeholder="请输入题目内容"
          />
        </el-form-item>
        <el-form-item label="选项" prop="options">
          <div
            v-for="(option, key) in optionList"
            :key="key"
            class="option-item"
          >
            <span class="option-key">{{ key }}.</span>
            <el-input v-model="optionList[key]" placeholder="请输入选项内容" />
            <el-radio
              v-model="form.correctAnswer"
              :label="key"
              class="option-radio"
            >
              正确答案
            </el-radio>
          </div>
        </el-form-item>
        <el-form-item label="分值" prop="score">
          <el-input-number
            v-model="form.score"
            :min="1"
            :max="100"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="难度" prop="difficulty">
          <el-select v-model="form.difficulty" placeholder="请选择难度">
            <el-option label="简单" value="EASY" />
            <el-option label="中等" value="MEDIUM" />
            <el-option label="困难" value="HARD" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getQuestions,
  addQuestion,
  updateQuestion,
  deleteQuestion,
} from "@/api/question";

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  subject: "",
  difficulty: "",
});

// 列表数据
const loading = ref(false);
const questionList = ref([]);
const total = ref(0);

// 表单数据
const dialogVisible = ref(false);
const dialogType = ref("add"); // add or edit
const formRef = ref(null);
const form = reactive({
  id: undefined,
  subject: "",
  questionText: "",
  options: {},
  correctAnswer: "",
  score: 1,
  difficulty: "MEDIUM",
});

// 选项列表
const optionList = reactive({
  A: "",
  B: "",
  C: "",
  D: "",
});

// 表单校验规则
const rules = {
  subject: [{ required: true, message: "请输入科目", trigger: "blur" }],
  questionText: [
    { required: true, message: "请输入题目内容", trigger: "blur" },
  ],
  correctAnswer: [
    { required: true, message: "请选择正确答案", trigger: "change" },
  ],
  score: [{ required: true, message: "请输入分值", trigger: "blur" }],
  difficulty: [{ required: true, message: "请选择难度", trigger: "change" }],
};

// 对话框标题
const dialogTitle = computed(() => {
  return dialogType.value === "add" ? "新增题目" : "编辑题目";
});

// 获取题目列表
const getList = async () => {
  loading.value = true;
  try {
    const { records, total: totalCount } = await getQuestions(queryParams);
    questionList.value = records;
    total.value = totalCount;
  } catch (error) {
    console.error("获取题目列表失败：", error);
  } finally {
    loading.value = false;
  }
};

// 查询按钮点击
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

// 重置按钮点击
const resetQuery = () => {
  queryParams.subject = "";
  queryParams.difficulty = "";
  handleQuery();
};

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.pageSize = val;
  getList();
};

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.pageNum = val;
  getList();
};

// 获取难度标签类型
const getDifficultyType = (difficulty) => {
  switch (difficulty) {
    case "EASY":
      return "success";
    case "MEDIUM":
      return "warning";
    case "HARD":
      return "danger";
    default:
      return "info";
  }
};

// 获取难度文本
const getDifficultyText = (difficulty) => {
  switch (difficulty) {
    case "EASY":
      return "简单";
    case "MEDIUM":
      return "中等";
    case "HARD":
      return "困难";
    default:
      return "未知";
  }
};

// 新增按钮点击
const handleAdd = () => {
  dialogType.value = "add";
  resetForm();
  dialogVisible.value = true;
};

// 编辑按钮点击
const handleEdit = (row) => {
  dialogType.value = "edit";
  resetForm();
  form.id = row.id;
  form.subject = row.subject;
  form.questionText = row.questionText;
  form.correctAnswer = row.correctAnswer;
  form.score = row.score;
  form.difficulty = row.difficulty;
  const options = JSON.parse(row.options);
  Object.keys(options).forEach((key) => {
    optionList[key] = options[key];
  });
  dialogVisible.value = true;
};

// 删除按钮点击
const handleDelete = (row) => {
  ElMessageBox.confirm("确认删除该题目吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await deleteQuestion(row.id);
      ElMessage.success("删除成功");
      getList();
    } catch (error) {
      console.error("删除题目失败：", error);
    }
  });
};

// 重置表单
const resetForm = () => {
  form.id = undefined;
  form.subject = "";
  form.questionText = "";
  form.correctAnswer = "";
  form.score = 1;
  form.difficulty = "MEDIUM";
  Object.keys(optionList).forEach((key) => {
    optionList[key] = "";
  });
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 处理选项
        const options = {};
        Object.keys(optionList).forEach((key) => {
          if (optionList[key]) {
            options[key] = optionList[key];
          }
        });
        form.options = options;

        if (dialogType.value === "add") {
          await addQuestion(form);
          ElMessage.success("新增成功");
        } else {
          await updateQuestion(form.id, form);
          ElMessage.success("修改成功");
        }
        dialogVisible.value = false;
        getList();
      } catch (error) {
        console.error("保存题目失败：", error);
      }
    }
  });
};

// 导入成功
const handleImportSuccess = (response) => {
  ElMessage.success("导入成功");
  getList();
};

// 导入失败
const handleImportError = (error) => {
  console.error("导入题目失败：", error);
  ElMessage.error("导入失败");
};

onMounted(() => {
  getList();
});
</script>

<style scoped>
.toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-form {
  flex: 1;
}

.toolbar-buttons {
  display: flex;
  gap: 10px;
  align-items: flex-start;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.option-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.option-key {
  margin-right: 10px;
  font-weight: bold;
}

.option-radio {
  margin-left: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
